package org.dragonnova.meetingserver.core.manager;

import android.content.Context;
import android.os.SystemClock;

import org.dragonnova.meetingserver.model.bean.MeetingInfo;
import org.dragonnova.meetingserver.utils.ContentResolverUtil;

/**
 * Created by hucn on 2016/6/17.
 * Description: 用于维护会议
 */
public class MeetingManager {

    private static MeetingManager mMeetingManager;
    private static MeetingInfo mMeetingInfo;
    private ContentResolverUtil mContentResolverUtil;

    private MeetingManager(Context context) {
        mContentResolverUtil = new ContentResolverUtil(context);
        MeetingInfo meetingInfo = mContentResolverUtil.findLatestMeeting();
        if (meetingInfo != null && meetingInfo.getFlag() == 1) {
            mMeetingInfo = meetingInfo;
        }
    }

    public static MeetingManager getInstance(Context context) {
        if (mMeetingManager == null) {
            synchronized (DeviceManager.class) {
                if (mMeetingManager == null) {
                    mMeetingManager = new MeetingManager(context);
                }
            }
        }
        return mMeetingManager;
    }

    public void createMeeting(MeetingInfo meetingInfo) {
        mContentResolverUtil.insertMeeting(meetingInfo);
        mMeetingInfo = meetingInfo;
    }

    public boolean createMeetingSafely(MeetingInfo meetingInfo) {
        if (mMeetingInfo == null) {
            createMeeting(meetingInfo);
            return true;
        }
        return false;
    }

    public void replaceMeeting(MeetingInfo meetingInfo) {
        closeMeeting();
        createMeeting(meetingInfo);
    }

    public boolean updateMeeting(MeetingInfo meetingInfo) {
        if (mMeetingInfo != null && mMeetingInfo.getSerial() == meetingInfo.getSerial()) {
            mMeetingInfo = meetingInfo;
            mContentResolverUtil.updataMeeting(mMeetingInfo);
            return true;
        }
        return false;
    }

    public void closeMeeting() {
        mMeetingInfo.setFlag(0);
        mContentResolverUtil.updataMeeting(mMeetingInfo);
        SystemClock.sleep(100);
        mMeetingInfo = null;
    }

    public MeetingInfo getcurrentMeeting() {
        return mMeetingInfo;
    }

    public boolean isMeetingCreated() {
        return mMeetingInfo != null;
    }
}
